package com.sudo.boot.netty.heartbeat;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.timeout.IdleStateEvent;

public class NettyHeartServerHandler extends SimpleChannelInboundHandler<String> {

    // 读超时次数
    int readIdleTimes = 0;

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String s) throws Exception {
        readIdleTimes = 0;
        System.out.println("服务端收到心跳：" + s);
        ctx.writeAndFlush("服务端收到心跳");
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt instanceof IdleStateEvent idleStateEvent) {
            switch (idleStateEvent.state()) {
                case READER_IDLE:
                    readIdleTimes++;
                    System.out.println("读超时");
                    break;
                case WRITER_IDLE:
                    System.out.println("写超时");
                    break;
                case ALL_IDLE:
                    System.out.println("读写超时");
                    break;
            }
            if (readIdleTimes > 3) {
                System.out.println("读超时超过3次");
                ctx.writeAndFlush("超时关闭");
                ctx.channel().close();
            }
        }
    }
}
